﻿using System;
using System.Data.Linq;
using Domain;

namespace Munimji.Controller
{
    public class Controller
    {
        private RepositoryDataContext repository;

        public Controller()
        {
            repository = new RepositoryDataContext();
        }

        public Profile CreateProfile(string title, string username, string password)
        {
            var profile = new Profile() {Title = title, Username = username, Password = password};
            repository.Profiles.InsertOnSubmit(profile);
            repository.SubmitChanges(ConflictMode.FailOnFirstConflict);
            return profile;
           
        }

        public Account CreateAccount(string title, bool? inFlowAccount, bool? outFlowAccount,Profile profile)
        {
            var account = new Account()
                              {
                                  Title = title,
                                  IsInFlowAccount = inFlowAccount,
                                  Profile = profile,
                                  IsOutFlowAccount = outFlowAccount,
                              };
            profile.Accounts.Add(account);
            repository.SubmitChanges(ConflictMode.FailOnFirstConflict);
            return account;
        }

        public Transaction TransferAmount(Profile profile, Account fromAccount, Account toAccount, double amount, DateTime transferDate, string description)
        {
            var transaction = new Transaction()
                               {
                                   ToAccount = toAccount,
                                   FromAccount = fromAccount,
                                   Profile = profile,
                                   Amount = amount,
                                   Date = transferDate,
                                   Description = description
                               };
            profile.Transactions.Add(transaction);
            repository.SubmitChanges(ConflictMode.FailOnFirstConflict);
            return transaction;
        }

        public void DeleteProfile(Profile profile)
        {
            repository.Profiles.DeleteOnSubmit(profile);
            repository.SubmitChanges(ConflictMode.FailOnFirstConflict);
        }

        public void DeleteAccount(Account account)
        {
            repository.Accounts.DeleteOnSubmit(account);
            repository.SubmitChanges(ConflictMode.FailOnFirstConflict);
        }

        public void DeleteTransaction(Transaction transaction)
        {
            repository.Transactions.DeleteOnSubmit(transaction);
            repository.SubmitChanges(ConflictMode.FailOnFirstConflict);
        }

        public void UpdateChanges()
        {
            repository.SubmitChanges();
        }
    }
}
